package net.xiaoxiangshop.controller.member;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import io.netty.util.internal.StringUtil;
import net.xiaoxiangshop.entity.MemberRank;
import net.xiaoxiangshop.entity.SocialUser;
import net.xiaoxiangshop.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.xiaoxiangshop.Results;
import net.xiaoxiangshop.entity.Member;
import net.xiaoxiangshop.entity.MemberAttribute;
import net.xiaoxiangshop.security.CurrentUser;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Controller - 个人资料
 * 
 */
@Controller("memberProfileController")
@RequestMapping("/member/profile")
public class ProfileController extends BaseController {

	@Inject
	private MemberService memberService;
	@Inject
	private MemberAttributeService memberAttributeService;
	@Inject
	private SmsService smsService;
	@Inject
	private RedisService redisService;
	@Inject
	private SocialUserService socialUserService;
	/**
	 * 检查E-mail是否唯一
	 */
	@GetMapping("/check_email")
	public @ResponseBody boolean checkEmail(String email, @CurrentUser Member currentUser) {
		return StringUtils.isNotEmpty(email) && !memberService.emailUnique(currentUser.getId(), email);
	}

	/**
	 * 检查手机是否唯一
	 */
	@GetMapping("/check_mobile")
	public @ResponseBody boolean checkMobile(String mobile, @CurrentUser Member currentUser) {
		return StringUtils.isNotEmpty(mobile) && !memberService.mobileUnique(currentUser.getId(), mobile);
	}

	/**
	 * 编辑
	 */
	@GetMapping("/edit")
	public String edit(ModelMap model) {
		model.addAttribute("genders", Member.Gender.values());
		return "member/profile/edit";
	}


	/**
	 * 更新
	 */
	@PostMapping("/update")
	public ResponseEntity<?> update(String email, String mobile, @CurrentUser Member currentUser, HttpServletRequest request) {
		if (!isValid(Member.class, "email", email) || !isValid(Member.class, "mobile", mobile)) {
			return Results.UNPROCESSABLE_ENTITY;
		}
		if (memberService.emailUnique(currentUser.getId(), email)) {
			return Results.UNPROCESSABLE_ENTITY;
		}
		if (memberService.mobileUnique(currentUser.getId(), mobile)) {
			return Results.UNPROCESSABLE_ENTITY;
		}
		currentUser.setEmail(email);
		currentUser.setMobile(mobile);
		currentUser.removeAttributeValue();
		for (MemberAttribute memberAttribute : memberAttributeService.findList(true, true)) {
			String[] values = request.getParameterValues("memberAttribute_" + memberAttribute.getId());
			if (!memberAttributeService.isValid(memberAttribute, values)) {
				return Results.UNPROCESSABLE_ENTITY;
			}
			Object memberAttributeValue = memberAttributeService.toMemberAttributeValue(memberAttribute, values);
			currentUser.setAttributeValue(memberAttribute, memberAttributeValue);
		}
		memberService.update(currentUser);
		return Results.OK;
	}
	@GetMapping("/binding")
	public String binding(ModelMap model) {
		return "member/profile/binding";
	}

	@GetMapping("/getSmsCode")
	public ResponseEntity<?> getSmsCode(String vipCard, @CurrentUser Member currentUser) {
		/**获取同步会员信息*/
		if(StringUtils.isEmpty(vipCard)){
			return Results.badRequest("会员卡号不能为空！");
		}
		String card=currentUser.getAttributeValue0();
		if(vipCard.equals(card)){
			return Results.badRequest("您的会员卡已绑定完成,无需重复绑定！");
		}
		Member member= memberService.synchroMember(currentUser,vipCard);
		if(member!=null){
			Integer time=smsService.sendSmsCode("0",member.getMobile());
			//先存入到redis
			Map<String,Object> memberMap=new HashMap<>();
			MemberRank memberRank = member.getMemberRank();
			memberMap.put("memberRank",memberRank.getId());
			memberMap.put("gender",member.getGender());
			memberMap.put("apoints",member.getApoints());
			memberMap.put("points",member.getPoints());
			memberMap.put("mobile",member.getMobile());
			redisService.set(currentUser.getId()+"",memberMap);
			return Results.ok("获取验证码成功，已发送至您的手机上！");
		}
		return Results.badRequest("获取验证码失败！");
	}
	@PostMapping("/bindingCard")
	public ResponseEntity<?> bindingCard(String vipCard,String smsCode, @CurrentUser Member currentUser) {
		if (StringUtils.isEmpty(vipCard)||StringUtils.isEmpty(smsCode)) {
			return Results.UNPROCESSABLE_ENTITY;
		}
		Object redisObj=redisService.get(currentUser.getId()+"");
		if(redisObj!=null){
			Map<String,Object> memberMap= (Map<String, Object>) redisObj;
			currentUser.setMobile(memberMap.get("mobile")+"");
			if(memberMap.get("points")!=null){
				currentUser.setPoints(new BigDecimal(memberMap.get("points")+""));
			}
			if(memberMap.get("apoints")!=null){
				currentUser.setApoints(new BigDecimal(memberMap.get("apoints")+""));
			}
			currentUser.setGender((Member.Gender) memberMap.get("gender"));
			MemberRank memberRank = currentUser.getMemberRank();
			memberRank.setId(Long.parseLong(memberMap.get("memberRank")+""));
			currentUser.setMemberRank(memberRank);

		ResponseEntity<?> reslut=smsService.checkSmsCode("0",currentUser.getMobile(),smsCode);
		Integer code= reslut.getStatusCodeValue();
		if(code!=200){//验证码不通过
			return reslut;
		}
		//判断卡号是否已经被其他用户绑定  如果绑定则解绑
		memberService.removeMemberCard(vipCard);
		memberService.update(currentUser);
		return Results.ok("会员卡绑定成功!");
		}else{
		return Results.ok("会员卡绑定失败!");
		}

	}



	/**
	 * 注销用户，更改用户状态
	 */
	@PostMapping("/zxUser")
	public ResponseEntity<?> zxUser(@CurrentUser Member currentUser) {
		currentUser.setIsEnabled(false);
		memberService.update(currentUser);
		//检查该用户是否绑定了扫码，小程序
		Set<SocialUser> socialUser= socialUserService.finByUserId(currentUser.getId());
		if(socialUser!=null&&socialUser.size()>0){
			for (SocialUser soc:socialUser){
				soc.setUser(null);
				socialUserService.update(soc);
			}
		}
		return Results.OK;
	}
}